package com.rzjm.api.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author by  zhouwei
 * @createtime 2017/12/14 14:45
 * @功能：
 */
public class ByteUtil {

    private final static char[] mChars = "0123456789ABCDEF".toCharArray();
    private final static String mHexStr = "0123456789ABCDEF";

    public static void main(String[] args) {
//        byte[] b = "31".getBytes();
//        String ss =  bytesToHexString(b);
//        System.out.println(" 31  16进制：" + ss);


        String ss1 =  int2Hex(31);
        System.out.println(" 31  16进制：" + ss1);


//        int e = getIntByHex("EB09");
//        System.out.println(e);
    }



    public static byte[] stringToAscii(String str, int length) {
        if (str == null) {
            return null;
        }
        byte[] result = new byte[length];
        for (int i = 0; i < str.length(); i++) {
            result[i] = (byte) str.charAt(i);
        }
        return result;
    }


    /**
     * 大端字节数组转字符串
     *
     * @param data
     * @return
     */
    public static String hex2String(byte[] data) {
        if (data == null) {
            return null;
        }
        StringBuilder str = new StringBuilder();
        for (byte aData : data) {
            str.append(String.format("%02X", aData));
        }

        return str.toString();
    }

    public static byte[] fileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            return bos.toByteArray();
        }
    }

    public static byte[] getPacket(byte[] originalBytes, int packetIndex, int packetSize) {
        if (originalBytes == null || packetIndex < 0 || packetSize <= 0) {
            throw new IllegalArgumentException("Invalid arguments");
        }

        int startIndex = packetIndex * packetSize;

        // 计算结束索引，确保不会超过原始数组长度
        int endIndex = Math.min(startIndex + packetSize, originalBytes.length);

        // 创建一个新的数组来存储这一包的数据
        byte[] packet = new byte[packetSize];

        // 复制原始数据到新数组
        System.arraycopy(originalBytes, startIndex, packet, 0, endIndex - startIndex);

        // 如果这一包的数据不足1024字节，则用0xFF填充剩余部分
        for (int i = endIndex - startIndex; i < packetSize; i++) {
            packet[i] = (byte) 0xFF;
        }

        return packet;
    }

    /**
     *  16进制转换成10进制
     * @param hex
     * @return
     */
    public static int getIntByHex(String hex){
        int decimal = Integer.parseInt(hex, 16);
//        System.out.println("数据： " + decimal);
        return decimal;
    }


    /**
     * 把字符串 转换成byte[]
     * @param s
     * @return
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return b;
    }

    /**
     * 字符串转换成十六进制字符串
     * @param str String 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str){
        StringBuilder sb = new StringBuilder();
        byte[] bs = str.getBytes();

        for (int i = 0; i < bs.length; i++){
            sb.append(mChars[(bs[i] & 0xFF) >> 4]);
            sb.append(mChars[bs[i] & 0x0F]);
//            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 10进制转16进制
     * @param num
     * @return
     */
    public static String int2Hex(int num){
        String hexNumber = Integer.toHexString(num);
//        System.out.println(hexNumber); // 输出 "ff"
        return hexNumber.toUpperCase();
    }



    public static String toHexString1(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }

    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s.toUpperCase();
        } else {
            return s.toUpperCase();
        }
    }

    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 获取 22 号命令的 写命令的开关的 请求数据
     * @param weiIndex
     * @param intDataIndex
     * @param OpenOrClose
     * @return
     */
    public static String getHexData(int weiIndex, int intDataIndex,String OpenOrClose){
        String s = "";
//        开 01160000  FFFF  0001
//        关 01160000  FFFE  0000
        //0000 0000 0000 0000
        if(OpenOrClose.equals("0")){//关闭
            for(int i = 0; i < intDataIndex; i++){
                if(weiIndex - 1 == i){
                    s+="0";
                }else{
                    s+="1";
                }
            }
        }else{//开启
            for(int i = 0; i < intDataIndex; i++){
                if(weiIndex - 1 == i){
                    s+="1";
                }else{
                    s+="0";
                }
            }
        }
        System.out.println("倒序之前："+s);
        s = StringUtil.daoxuStr(s);
        System.out.println("倒序之后："+s);
        s = binaryString2hexString(s).toUpperCase();
        if(OpenOrClose.equals("0")){//关闭
            s = s + "0000";
        }else{
            s = "FFFF" + s;
        }
        return s;
    }

    /**
     * 把 二进制数据 转换成16进制  字符串
     * @param bString
     * @return
     */
    public static String binaryString2hexString(String bString){
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)
            return null;
        StringBuffer tmp = new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4)
        {
            iTmp = 0;
            for (int j = 0; j < 4; j++)
            {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }

    /**
     * 十六转二进制
     *
     * @param hex
     *            十六进制字符串
     * @return 二进制字符串
     */
    public static String hexStringToBinary(String hex) {
        hex = hex.toUpperCase();
        String result = "";
        int max = hex.length();
        for (int i = 0; i < max; i++) {
            char c = hex.charAt(i);
            switch (c) {
                case '0':
                    result += "0000";
                    break;
                case '1':
                    result += "0001";
                    break;
                case '2':
                    result += "0010";
                    break;
                case '3':
                    result += "0011";
                    break;
                case '4':
                    result += "0100";
                    break;
                case '5':
                    result += "0101";
                    break;
                case '6':
                    result += "0110";
                    break;
                case '7':
                    result += "0111";
                    break;
                case '8':
                    result += "1000";
                    break;
                case '9':
                    result += "1001";
                    break;
                case 'A':
                    result += "1010";
                    break;
                case 'B':
                    result += "1011";
                    break;
                case 'C':
                    result += "1100";
                    break;
                case 'D':
                    result += "1101";
                    break;
                case 'E':
                    result += "1110";
                    break;
                case 'F':
                    result += "1111";
                    break;
            }
        }
        return result;
    }
}
